package com.zzld.modules.sys.action;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.github.abel533.entity.Example;
import com.github.pagehelper.PageInfo;
import com.zzld.core.utils.MD5Util;
import com.zzld.core.utils.MessageUtils;
import com.zzld.core.utils.UuidUtil;
import com.zzld.modules.common.dto.CommonJSON;
import com.zzld.modules.sys.entity.Login;
import com.zzld.modules.sys.entity.User;
import com.zzld.modules.sys.security.ShiroUser;
import com.zzld.modules.sys.service.ILoginService;
import com.zzld.modules.sys.service.IUserRoleService;
import com.zzld.modules.sys.service.IUserService;

@Controller
@RequestMapping("/sys/user")
public class UserController {

	@Autowired
	private IUserService userService;

	@Autowired
	private ILoginService loginService;
	
	@Autowired
	private IUserRoleService userroleService;	
	

	private String listurl = "/modules/sys/user/userList";
	private String cururl = "/modules/sys/user/userCru";
	private String quanurl = "/modules/sys/user/userGrant";
	private String uploadurl ="/modules/sys/user/userUpload";
	private String userpass = "/modules/sys/user/userpass";

	@RequestMapping("/adupdate/pro")
	public String cur() {
		return cururl;
	}
	
	@RequestMapping(value="pass")
	public String pass(){
		return userpass;
	}
	

	@RequestMapping(method = RequestMethod.GET)
	public String user(Model model, HttpServletRequest request) {

		return listurl;
	}

	@RequestMapping(value = "/usergrant/tree/pro")
	public String userupdate(HttpServletRequest request, Model model) {
		model.addAttribute("userid", request.getParameter("id"));
		return quanurl;
	}

	@RequestMapping(value = "/adupdate/pro/json")
	@ResponseBody
	public JSONObject selectbyid(HttpServletRequest request) {
		String id = request.getParameter("id");
		JSONObject paramJson = new JSONObject();

		if (id != null) {
			Map<String, Object> rfaw = new HashMap<String, Object>();
			rfaw.putAll(userService.selectbyid(id));
			paramJson.putAll(rfaw);

		}
		return paramJson;

	}

	/**
	 * 新增/修改操作
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/adupdate", method = RequestMethod.POST)
	@ResponseBody
	public CommonJSON adupdate(Model model, User entity, Login login,
			HttpServletRequest request, HttpSession session) {
		ShiroUser userq = (ShiroUser) SecurityUtils.getSubject().getPrincipal();

		CommonJSON resultJson = new CommonJSON();
		login.setCreateDate(new Date());
		login.setCreateBy(userq.getName());
		if (StringUtils.isBlank(entity.getLid())) {// 新增
			entity.setLid(UuidUtil.uuid().toString());// 自己生成id
			login.setId(entity.getLid());// 生成loginid
			login.setPasswd(MD5Util.encoderByMd5With32Bit("123456"));
			//login.setPasswd("e10adc3949ba59abbe56e057f20f883e");// 后期修改
			try {

				if (loginService.saveSelective(login) > 0) {
					entity.setAccount(null);
					entity.setUsername(null);
					entity.setCreate_date(null);
					userService.savesetive(entity);
					resultJson.setSuccess(true);
					resultJson.setMessage(MessageUtils.ADD_SUCCESS);
				} else {
					resultJson.setSuccess(false);
					resultJson.setMessage(MessageUtils.ADD_FAIL);
				}

			} catch (Exception e) {
				e.printStackTrace();
				resultJson.setSuccess(false);
				resultJson.setMessage(MessageUtils.ADD_FAIL);
			}
		} else {
			try {
				login.setId(entity.getLid());
				if (loginService.updateLoginUser(login) > 0) {
					int q = userService.updateUser(entity);
					resultJson.setSuccess(true);
					resultJson.setMessage(MessageUtils.EDIT_SUCCESS);
				} else {
					resultJson.setSuccess(false);
					resultJson.setMessage(MessageUtils.EDIT_WARING);
				}

			} catch (Exception e) {
				e.printStackTrace();
				resultJson.setSuccess(false);
				resultJson.setMessage(MessageUtils.EDIT_WARING);
			}
		}
		return resultJson;
	}

	@RequestMapping(value = "list")
	@ResponseBody
	public CommonJSON list(HttpServletRequest request) {

		int pageNum = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		String sort = request.getParameter("sort") == "seq" ? "name" : request
				.getParameter("sort");
		if (sort.equals("createDate")) {
			sort = "create_date";
		}

		CommonJSON json = new CommonJSON();
		Map<String, String> map = new HashMap<String, String>();
		map.put("sort", request.getParameter("sort") == "seq" ? "sort"
				: request.getParameter("sort"));
		map.put("order", request.getParameter("order"));
		map.put("login", request.getParameter("QUERY_t#loginname_S_LK"));
		map.put("name", request.getParameter("QUERY_t#name_S_LK"));
		map.put("sex", request.getParameter("QUERY_t#sex_S_EQ"));
		map.put("createGe", request.getParameter("QUERY_t#createdatetime_D_GE"));
		map.put("createLe", request.getParameter("QUERY_t#createdatetime_D_LE"));

		PageInfo page = userService.selectjoinuser(map, pageNum, pageSize);
		json.setRows(page.getList());
		json.setTotal(page.getTotal());
		return json;
	}

	@RequestMapping(value = "exportXls")
	public String exportXls(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("sort", "sort");
		map.put("order", "desc");
		map.put("login", null);
		map.put("name", null);
		map.put("sex", null);
		map.put("createGe", null);
		map.put("createLe", null);
		List<User> user = userService.selectAll(map);
		return null;

	}
	
	
	@RequestMapping(value = "upload")
	public String upload(HttpServletRequest req) {
		return uploadurl;
	}
	
	@RequestMapping(value = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public CommonJSON importExcel(HttpServletRequest request, HttpServletResponse response) {
		CommonJSON cj= new CommonJSON();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);	
			params.setNeedSave(true);
			try {
				List<User> listUser=ExcelImportUtil.importExcel(file.getInputStream(), User.class,params);
				for (User user : listUser) {
					if(user.getUsername()!=null){
						userService.save(user);
					}
				}
				cj.setSuccess(true);
				cj.setMessage("文件导入成功！");
			} catch (Exception e) {
				cj.setSuccess(false);
				cj.setMessage("文件导入失败！");
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return cj;
	}

	/**
	 * 删除操作
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public CommonJSON delete(HttpServletRequest request,
			@PathVariable("id") String id) {
		CommonJSON resultJson = new CommonJSON();

		// 执行删除
		try {

			if (userService.delusercall(id) > 0) {
				userroleService.selectbyusid(id);
				resultJson.setMessage(MessageUtils.DELETE_SUCCESS);
			} else {
				resultJson.setMessage(MessageUtils.EDIT_WARING);
			}

		} catch (Exception e) {
			e.printStackTrace(); 
			resultJson.setMessage(MessageUtils.EDIT_WARING);
		}
		return resultJson;
	}
	
	@RequestMapping(value="updatepass",method=RequestMethod.POST)
	@ResponseBody
	public CommonJSON updatepass(HttpServletRequest request,Model model){
		CommonJSON json = new CommonJSON();
		ShiroUser userq = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    
		try{
		    Login login = new Login();
		    login = loginService.selectByPrimaryKey(userq.getId());
            login.setPasswd(MD5Util.encoderByMd5With32Bit(request.getParameter("password").toString()));
		    if(loginService.updateByPrimaryKeySelective(login)>0){
		    	json.setMessage(MessageUtils.EDIT_SUCCESS);
		    	json.setSuccess(true);
		    }else{
		    	json.setMessage(MessageUtils.EDIT_WARING);
		    	json.setSuccess(false);
		    }
		    
		}catch(Exception e){
			json.setMessage(MessageUtils.EDIT_WARING);
	    	json.setSuccess(false);
		}
		
		return json;
	}

}
